﻿using EnglishStudy.Entity;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace EnglishStudy.ViewModel
{
    class HomePageViewModel : INotifyPropertyChanged
    {
        private LessonDataContext lessonDB;
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        // Class constructor, create the data context object.
        public HomePageViewModel(string lessonDBConnectionString)
        {
            lessonDB = new LessonDataContext(lessonDBConnectionString);
            //LoadCollectionsFromDatabase();
            // Specify the query for all to-do items in the database.
            ////var newWord = from WordTable item in lessonDB.WordList
            ////              where item.Frequency == 1
            ////              select item;

            ////// Query the database and load all to-do items.
            ////NewWordList = new ObservableCollection<WordTable>(newWord);
        }


        private string _totalTime;
        public string TotalTime
        {
            get { return _totalTime; }
            set
            {
                _totalTime = value;
                NotifyPropertyChanged("TotalTime");
            }
        }


        private ObservableCollection<Country> _languageList;
        public ObservableCollection<Country> LanguageList
        {
            get { return _languageList; }
            set
            {
                _languageList = value;
                NotifyPropertyChanged("LanguageList");
            }
        }

        // A list of all new word
        private int _numberWordLearned;
        public int NumberWordLearned
        {
            get { return _numberWordLearned; }
            set
            {
                _numberWordLearned = value;
                NotifyPropertyChanged("NumberWordLearned");
            }
        }

        // A list of all miss pronounced word
        private double _score;
        public double Score
        {
            get { return _score; }
            set
            {
                _score = value;
                NotifyPropertyChanged("Score");
            }
        }

        // A list of all miss pronounced word
        private int _lessonCompleted;
        public int LessonCompleted
        {
            get { return _lessonCompleted; }
            set
            {
                _lessonCompleted = value;
                NotifyPropertyChanged("LessonCompleted");
            }
        }

        // Query database and load the word list.
        public void LoadCollectionsFromDatabase()
        {
            NumberWordLearned = wordsLearned();
            Score = App.ViewModel.UserInfo.Score;
            LessonCompleted = getLessonCompleted();
            LanguageList = getCountriesList();
            TotalTime = ToReadableString(getTotalTime());
        }

        public string ToReadableString(TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}{3}",
                span.Duration().Days > 0 ? string.Format("{0:0} day{1}, ", span.Days, span.Days == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Hours > 0 ? string.Format("{0:0} hour{1}, ", span.Hours, span.Hours == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Minutes > 0 ? string.Format("{0:0} min{1}, ", span.Minutes, span.Minutes == 1 ? String.Empty : "s") : string.Empty,
                span.Duration().Seconds > 0 ? string.Format("{0:0} sec{1}", span.Seconds, span.Seconds == 1 ? String.Empty : "s") : string.Empty);
            if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);
            if (string.IsNullOrEmpty(formatted)) formatted = "0 sec";
            return formatted;
        }

        public TimeSpan getTotalTime()
        {
            if (settings.Contains("TotalTime"))
            {
                return (TimeSpan)settings["TotalTime"];
            }
            else
                settings.Add("TotalTime", new TimeSpan(0, 0, 0));

            return new TimeSpan(0, 0, 0);
        }
        public ObservableCollection<Country> getCountriesList()
        {
            // Specify the query for all to-do items in the database.
            var languageItem = from Country item in lessonDB.Countries
                                select item;

            // Query the database and load all to-do items.
            ObservableCollection<Country> LanguageItems = new ObservableCollection<Country>(languageItem);
            return LanguageItems;
        }

        public int wordsLearned()
        {
            List<WordTable> commonWord = (from WordTable wordItem in lessonDB.WordList
                                          where wordItem.IsLearned == true
                                          select wordItem).ToList();
            if (commonWord != null && commonWord.Count > 0)
                return commonWord.Count;
            else
                return 0;
        }

        public int getLessonCompleted()
        {
            List<LessonItem> listLesson = (from LessonItem item in lessonDB.LessonItems
                                           where item.IsComplete == true
                                           select item).ToList();
            return listLesson.Count;
        }

        // Write changes in the data context to the database.
        public void SaveChangesToDB()
        {
            lessonDB.SubmitChanges();
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed.
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}
